package com.abdu.demo.kotlindemo

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HomeActivity : AppCompatActivity() {
    private var context: Context = this
    private lateinit var sharedPreferences: SharedPreferences

    private lateinit var timeText: TextView
    private lateinit var tv_account: TextView
    private lateinit var btn_logOut: Button
    private val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        timeText = findViewById(R.id.timeText)
        tv_account = findViewById(R.id.tv_account)
        btn_logOut = findViewById(R.id.btn_logOut)

        initObject()
        updateTime()
        logout()

    }

    private fun updateTime() {
        handler.postDelayed({
            val time = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
            timeText.text = time
            updateTime()
        }, 1000)
    }

    private fun initObject() {
        sharedPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE)

        val account: String? = sharedPreferences.getString("account", "")
        if (account?.length!! > 0) {
            showToast("欢迎您，${account}")
            tv_account.text = "用户『${account}』您好！"
            return
        } else {
            showToast("未登录")
            startActivity(Intent(context, loginActivity::class.java))
            finish()
        }
    }

    fun logout() {
       btn_logOut.setOnClickListener {
           sharedPreferences.edit().clear().apply()
           startActivity(Intent(context, loginActivity::class.java))
           finish()
       }

    }

    private fun showToast(text: String){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
    }
}